<%@ Page Language="c#" CodeBehind="CategoryMoveDialog.aspx.cs" MasterPageFile="../../../masterpages/umbracoDialog.Master" AutoEventWireup="True" Inherits="Auros.Categorisation.Umbraco.Dialogs.CategoryMoveDialog" %>
<%@ Register TagPrefix="umb" Namespace="ClientDependency.Core.Controls" Assembly="ClientDependency.Core" %>
<%@ Register TagPrefix="cc1" Namespace="umbraco.uicontrols" Assembly="controls" %>
<%@ Register Src="~/umbraco/controls/Tree/TreeControl.ascx" TagName="TreeControl" TagPrefix="umbraco" %>

<%@ Import Namespace="Auros.Categorisation.Umbraco" %>

<asp:Content ContentPlaceHolderID="head" runat="server">
    <script type="text/javascript">

        Array.prototype.contains = function(obj) {
            var i = this.length;
            while (i--) {
                if (this[i] === obj) {
                    return true;
                }
            }
            return false;
        }
	
        var categories = new Object();
            
        var currentCategory;
        var currentCategoryDescendants = new Array();
        var selectedCategory;
        var actionIsValid = true;

        function getDescendants(category)
        {
            for(var i = 0; i < category.Children.length; i++)
            {
                currentCategoryDescendants.push(category.Children[i].ID);
        
                if(category.Children)
                {
                    getDescendants(category.Children[i]);
                }
            }
        }
			
        function getCategory(id, callback) {
            $.ajax({
                type: "GET",
                url: "<%= umbraco.IO.IOHelper.ResolveUrl(umbraco.IO.SystemDirectories.Umbraco)%>/webservices/categorisation/GetCategory?id=" + id,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: callback,
                    error: function (response) {	
                        console.log("Error occured retrieving data for category with ID '" + id + "'. Result: " + result);
                        displayError('An error ocurred, please try again.');
                    }
			});
        }
			
        function displayError(message) {
            jQuery("#categoryNameContent").html(message);
            jQuery("#categoryNameHolder").attr("class", "error");
        }
			
        function displaySuccess(message) {
            jQuery("#categoryNameContent").html(message);
            jQuery("#categoryNameHolder").attr("class", "success");
        }
			
        function validateAction(newParentId)
        {
            if(currentCategory.ParentID === newParentId) {
                displayError("You've selected the current parent, select a different destination category to move it there or click cancel to keep the category where it is.");
                return false;
            } else if(currentCategory.ID === newParentId) {
                displayError("You can't move a category to itself, select a different destination category.");
                return false;
            } else if(currentCategoryDescendants.contains(newParentId)) {
                displayError("You can't move a category to a descendant of itself, select a different destination category.");
                return false;
            }

            return true;
        }
			
        function dialogHandler(id) {				
            if(typeof categories[id] !== "undefined") {
                selectedCategory = categories[id];
                console.log('Category retreived from collection.');
                console.log('Category selected: ' + selectedCategory.Name + ' (' + selectedCategory.ID + ').');

                if(validateAction(selectedCategory.ID))
                {
                    document.getElementById("NewParentId").value = id;
                    document.getElementById("<%= this.OkButton.ClientID %>").disabled = false;
                    updateName(selectedCategory.Name);
                }
                else
                {
                    document.getElementById("<%= this.OkButton.ClientID %>").disabled = true;
                }
            } else {
                getCategory(id, function(data) {
                    selectedCategory = data;
                    categories[id] = selectedCategory;
                    console.log('Category selected: ' + selectedCategory.Name + ' (' + selectedCategory.ID + ').');

                    if(validateAction(selectedCategory.ID))
                    {
                        document.getElementById("NewParentId").value = id;
                        document.getElementById("<%= this.OkButton.ClientID %>").disabled = false;
                        updateName(selectedCategory.Name);
                    }
                    else
                    {
                        document.getElementById("<%= this.OkButton.ClientID %>").disabled = true;
                    }
                });
            }
        }

        function updateName(result) {
            displaySuccess(currentCategory.Name + " will be moved under '<strong>" + result + "</strong>'.");
        }
			
        $(document).ready(function() {
			
            getCategory(<%= umbraco.helper.Request("id") %>, function(data) {
                currentCategory = data;
                getDescendants(currentCategory);
			});
				
			var timer = setInterval(function(){
			    if ($('li#init > a').length > 0) {
			        $('li#init > a').click(function() {

			            if(validateAction(0))
			            {
			                document.getElementById("NewParentId").value = 0;
			                document.getElementById("<%= this.OkButton.ClientID %>").disabled = false;
			                updateName('root');
                        }
                        else
                        {
                            document.getElementById("<%= this.OkButton.ClientID %>").disabled = true;
                        }
						
					});
						
                    clearInterval(timer);  
                }
			},50); 
				
		}); 
    
    </script>

    <style type="text/css">
        .propertyItemheader
        {
            width: 180px !important;
        }
    </style>
</asp:Content>
<asp:Content ContentPlaceHolderID="body" runat="server">
    <umb:JsInclude ID="JsInclude" runat="server" FilePath="js/umbracoCheckKeys.js" PathNameAlias="UmbracoRoot" />

    <input type="hidden" id="NewParentId" name="NewParentId" />

    <cc1:Feedback ID="Feedback" runat="server" />

    <cc1:Pane ID="TreePane" runat="server" Visible="false">
        <cc1:PropertyPanel runat="server" Style="overflow: auto; height: 220px; position: relative;">
            <umbraco:TreeControl runat="server" ID="JTree" App="settings" TreeType="categories" IsDialog="true" DialogMode="id" ShowContextMenu="false" FunctionToCall="dialogHandler" Height="200"></umbraco:TreeControl>
        </cc1:PropertyPanel>
    </cc1:Pane>

    <asp:PlaceHolder ID="NoticePane" runat="server" Visible="false">
        <div class="notice" id="categoryNameHolder" style="margin-top: 10px;">
            <p id="categoryNameContent">
                <%= UIHelpers.GetLocalisedText("noNodeSelected", "moveOrCopy") %>
            </p>
        </div>
    </asp:PlaceHolder>

    <asp:Panel ID="ButtonsPane" runat="server">
        <p>
            <asp:Button ID="OkButton" runat="server" CssClass="guiInputButton" OnClick="OkButtonClick"></asp:Button>
            <em> <%= UIHelpers.GetLocalisedText("or", "general") %> </em>
            <a href="#" style="color: blue" onclick="UmbClientMgr.closeModalWindow()"><%= UIHelpers.GetLocalisedText("cancel", "general") %></a>
        </p>
    </asp:Panel>
</asp:Content>
